<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\Notice\Models\IpGeo;
use Modules\Notice\Models\Sms;
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;


class NoticeController extends Controller
{
    protected $logger;
    protected $caller;
    protected $requestId;

    public function __construct(Request $request)
    {
        $this->requestId = time().rand(10000, 99999);
        $this->logger = new Logger('notice');
        $logPath = storage_path('logs/notice.log');
        $this->logger->pushHandler(new RotatingFileHandler($logPath, 30));
        $request->request->add(['requestId' => $this->requestId]);
        $this->logger->info($request->path() . ' request', $request->all());
        $this->caller = $request->path();
    }

    /**
     * 发送短信验证码
     * @param Request $request
     * @return JsonResponse
     */
    public function sendCode(Request $request)
    {
        $phone = $request->input('phone');
        if (empty($phone)) {
            return $this->response($this->caller, $this->requestId, 500, '手机号不能为空');
        }
        // 校验手机号格式
        if (!preg_match('/^1[3456789]\d{9}$/', $phone)) {
            return $this->response($this->caller, $this->requestId, 500, '手机号格式不正确');
        }
        $smsMode = new Sms();
        $res = $smsMode->send_code($phone);
        if ($res) {
            return $this->response($this->caller, $this->requestId, 200, '发送成功');
        } else {
            return $this->response($this->caller, $this->requestId, 500, '发送失败');
        }
    }

    /**
     * 获取ip信息
     * @param Request $request
     * @return JsonResponse
     */
    public function ipGeo(Request $request)
    {
        $ip = $request->input('ip', $request->ip());
        if (empty($ip)) {
            return $this->response($this->caller, $this->requestId, 500, 'ip不能为空');
        }
        $ipGeo = new IpGeo();
        $res = $ipGeo->geo($ip);
        if ($res) {
            return $this->response($this->caller, $this->requestId, 200, '获取成功', $res);
        } else {
            return $this->response($this->caller, $this->requestId, 500, '获取失败');
        }
    }
}
